﻿using MudEngine.Parsing;
using MudEngine.Runtime;
using MudEngine.Utils;
using System;
using System.Threading;

namespace MudEngine.Program
{
	class Program
	{
		static void Main(string[] args)
		{
			Program p = new Program();
			p.Start();
		}

		public void Start()
		{
            int[] k = new int[10];
            k[4] = 5;

            bool running = true;
			Log.Init("logConfig.xml", true);

            Interpreter interpreter = new Interpreter();
            Compiler compiler = new Compiler();
            ObjectManager objectManager = new ObjectManager();

            objectManager.Interpreter = interpreter;
            objectManager.Compiler = compiler;
            interpreter.ObjectManager = objectManager;
            compiler.Interpreter = interpreter;
            compiler.ObjectManager = objectManager;

            object_t masterObject = objectManager.LoadObject(MudContext.DRIVER);
            if (masterObject == null)
            {
                throw new Exception("Master not loaded");
            }
            masterObject.Flags |= ObjectFlags.O_MASTER;

            CommunicationManager commManager = new CommunicationManager(4000, 5, masterObject);
            commManager._interpreter = interpreter;
            commManager.Start();

            //CPUGovernor governor = new CPUGovernor(5);
            ErrorContext econ = new ErrorContext();
            interpreter.Context.SaveContext(econ);

            while (running)
            {
                try
                {
                    commManager.ProcessIO();

                    objectManager.CleanUp();
                }
                catch (RuntimeException e)
                {
                    Console.WriteLine(e.ToString());
                    interpreter.Context.RestoreContext(econ);
                }
                //governor.Sleep();
                Thread.Sleep(1);
            }

			//ObjectCompiler.Instance.StartFileWatcher(MudContext.LIB_DIR);

			//CommandStringParser p = CommandStringParser.Instance;
		}
	}
}
